package io.adrainty.bolee.framework.gateway.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.lang.Nullable;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/7/27 下午10:43
 */

@SuppressWarnings("unused")
public class RequestHelper {

    private RequestHelper() {}

    /**
     * 获取媒体类型编码
     * @param mediaType 媒体类型
     * @return 编码
     */
    public static Charset getMediaTypeCharset(@Nullable MediaType mediaType) {
        if (Objects.nonNull(mediaType) && mediaType.getCharset() != null) {
            return mediaType.getCharset();
        } else {
            return StandardCharsets.UTF_8;
        }
    }

    /**
     * 判断是否是上传文件请求
     * @param mediaType 媒体类型
     * @return 是否是上传文件请求
     */
    public static boolean isUploadFileRequest(@Nullable MediaType mediaType) {
        if (Objects.isNull(mediaType)) {
            return false;
        }
        return mediaType.includes(MediaType.MULTIPART_FORM_DATA)
                || mediaType.includes(MediaType.IMAGE_GIF)
                || mediaType.includes(MediaType.IMAGE_JPEG)
                || mediaType.includes(MediaType.IMAGE_PNG)
                || mediaType.equals(MediaType.MULTIPART_FORM_DATA);
    }

    public static String getFirstHeader(ServerHttpRequest request, String headerName) {
        return request.getHeaders().getFirst(headerName);
    }

    public static String getFirstHeaderDefault(ServerHttpRequest request, String headerName, String defaultValue) {
        return StringUtils.defaultIfBlank(request.getHeaders().getFirst(headerName), defaultValue);
    }

}
